"""
应用配置管理
"""
from typing import List, Optional
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import field_validator
import os
from pathlib import Path


class Settings(BaseSettings):
    """应用设置"""

    # 配置模型
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore"
    )

    # 应用基础配置
    app_name: str = "系统操作助手"
    app_version: str = "1.0.0"
    debug: bool = False
    host: str = "0.0.0.0"
    port: int = 8000
    
    # 数据库配置
    database_url: str = "sqlite:///./system_assistant.db"
    
    # AI模型配置
    openai_api_key: Optional[str] = None
    openai_model: str = "gpt-3.5-turbo"
    openai_base_url: str = "https://api.openai.com/v1"
    
    # 向量数据库配置
    chroma_persist_directory: str = "./data/chroma_db"

    # 嵌入模型配置（仅支持API模式）
    embedding_model: str = "doubao-embedding-vision-250615"
    embedding_api_key: Optional[str] = None
    embedding_api_base_url: str = "https://ark.cn-beijing.volces.com/api/v3"
    
    # 安全配置
    secret_key: str = "your-secret-key-change-in-production"
    access_token_expire_minutes: int = 30
    algorithm: str = "HS256"
    
    # 日志配置
    log_level: str = "INFO"
    log_file: str = "./logs/app.log"
    
    # 知识库配置
    knowledge_base_path: str = "./data/knowledge_base"
    max_search_results: int = 5
    similarity_threshold: float = 0.3  # 降低相似度阈值

    # CORS配置
    allowed_origins: str = "http://localhost:3000,http://127.0.0.1:3000"

    @field_validator("allowed_origins")
    @classmethod
    def parse_allowed_origins(cls, v):
        """解析允许的源"""
        if isinstance(v, str):
            return [origin.strip() for origin in v.split(",")]
        return v



# 创建全局设置实例
settings = Settings()

# 调试：检查.env文件加载情况
def check_env_loading():
    """检查环境变量加载情况"""
    env_file_path = Path(".env")
    print(f"🔍 检查.env文件加载情况:")
    print(f"   .env文件路径: {env_file_path.absolute()}")
    print(f"   .env文件存在: {env_file_path.exists()}")

    if env_file_path.exists():
        print(f"   .env文件大小: {env_file_path.stat().st_size} 字节")
        # 读取前几行内容（不显示敏感信息）
        try:
            with open(env_file_path, 'r', encoding='utf-8') as f:
                lines = f.readlines()[:5]  # 只读前5行
            print(f"   .env文件行数: {len(lines)}")
            for i, line in enumerate(lines, 1):
                if '=' in line and not line.startswith('#'):
                    key = line.split('=')[0].strip()
                    print(f"   第{i}行: {key}=***")
        except Exception as e:
            print(f"   读取.env文件失败: {e}")

    print(f"   当前工作目录: {Path.cwd()}")
    print(f"   OPENAI_API_KEY已加载: {'是' if settings.openai_api_key else '否'}")
    print(f"   EMBEDDING_API_KEY已加载: {'是' if settings.embedding_api_key else '否'}")

# 在开发模式下检查环境变量加载
if os.getenv("DEBUG", "false").lower() == "true":
    check_env_loading()

# 确保必要的目录存在
def ensure_directories():
    """确保必要的目录存在"""
    directories = [
        Path(settings.chroma_persist_directory).parent,
        Path(settings.knowledge_base_path),
        Path(settings.log_file).parent,
    ]
    
    for directory in directories:
        directory.mkdir(parents=True, exist_ok=True)


# 初始化时创建目录
ensure_directories()
